package cn.com.callback

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
 * @author ThinkPad
 */

public class ensign implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(ensign.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
		log.debug('==================================加密处理=================================================');	
		def receivebody = Util.getRequestBody(request,"utf-8"); //获取报文
		JSONObject obj = JSONObject.fromObject(receivebody);
		def secretkey = obj.get("secretkey"); //获取密钥
		obj.remove("secretkey"); //	去除密钥			
		obj.remove("sign"); //去除签名
		if(Util.filterForObject(obj.get("timestamp"))==""){
			obj.put("timestamp",new Date().getTime() + ""); //加入时间戳		
		};
		def mapStr = assemble(obj);    //原始Map拼接成：keyvalue...keyvalue格式		
		def encryptstr = Util.getMD5Str(mapStr); // 第一次加密，拼接之后的原始字符串进行md5加密
		encryptstr = Base64.encode(encryptstr+secretkey,"utf-8"); // 第二次加密，base64加密，加上秘钥(由接收方提供)
		encryptstr = Util.getMD5Str(encryptstr); // 第三次加密，再次进行md5加密
		encryptstr = encryptstr.toUpperCase(); //转大写
		obj.put("sign",encryptstr);		
		return JSONObject.fromObject(obj).toString();
	}
	public String assemble(JSONObject params) {
		// 1.sort：先按照map的key值进行排序
		Object[] keyArr = new Object[params.size()];
		params.keySet().toArray(keyArr);
		Arrays.sort(keyArr);

		// 2.拼接成：keyvalue...keyvalue字符串
		StringBuffer queryString = new StringBuffer();
		for (Object key : keyArr) {
			Object val = params.get(key);
			if (val != null) {
				queryString.append(key);
				if (val instanceof Boolean) {
					boolean flag = (Boolean) val;
					queryString.append(flag ? 1 : 0);
				} else{
					queryString.append(val);
				}
			}
		}
		return queryString.toString();
	}
    	
}